package test.wph;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Description 实现一个线程安全的 BlockingQueue
 * @Author Firenut
 * @Date 2023-08-21 17:26
 */
public class BlockingQueueDemo<T> {
    @Test
    public void test() throws InterruptedException {
        BlockingQueueDemo<Integer> bq = new BlockingQueueDemo<>();
        for (int i = 0; i < 10; i++) {
            new Thread(){
                @Override
                public void run() {
                    bq.add(1);
                    System.out.println();
                }
            }.start();
        }

        Thread.sleep(5000);
        for (int i = 0; i < bq.list.size(); i++) {
            System.out.println(bq.list.get(i));
        }
    }

    List<T> list = new ArrayList<>();
    ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    Lock readLock = lock.readLock();
    Lock writeLock = lock.writeLock();

    T get(int index) {
        try{
            readLock.lock();
            T t = list.get(index);
            return t;
        }finally {
            readLock.unlock();
        }
    }

    void add(T obj) {
        try {
            writeLock.lock();
            list.add(obj);
        } finally {
            writeLock.unlock();
        }
    }

    void remove(T obj) {
        try {
            writeLock.lock();
            list.remove(obj);
        }finally {
            writeLock.unlock();
        }
    }

    void put(int index, T obj) {
        try {
            writeLock.lock();
            if (list.contains(obj)) {
                list.add(index, obj);
            }
        }finally {
            writeLock.unlock();
        }
    }
}
